import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';

class View1 extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new View1State();
  }
}

class View1State extends State<View1> {
  var _newsList = [];
  Future _getData() async{
    Response response = await Dio().get("http://jsonplaceholder.typicode.com/photos");
    // setState(() {
    //   _newsList = response.data;
    // });
    if(!mounted) return [];
    return response.data;
  }
  Future refreshData() async{
    await _getData();   //注意await关键字
    if (!mounted) return; //异步处理，防止报错
    setState(() {});//什么都不做，只为触发RefreshIndicator的子控件刷新
  }
  @override
  void initState() {
    super.initState();
    // _getData();
  }
  @override
  Widget build(BuildContext context) {
    // return _newsList.length > 0 ? new ListView.builder(
    //     itemBuilder: (_, i) {
    //       var news = _newsList[i];
    //       return new Card(
    //         child: new Column(
    //           crossAxisAlignment: CrossAxisAlignment.start,
    //           children: <Widget>[
    //             new Text('title:' + news['title']),
    //             new Image.network(news['thumbnailUrl'])
    //           ],
    //         ),
    //       );
    //     },
    //     itemCount: _newsList.length,
    //   ) : new Center(child: new Text('loading...'));
    return new RefreshIndicator(// 下拉刷新容器
      child: new FutureBuilder(
        future: _getData(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.none:
            case ConnectionState.waiting:
              return new Center(child: new Text('loading...'));
              break;
            default:
            if(snapshot.hasError){
              return new Center(child: new Text(snapshot.error));
            }
            else {
              return _renderData(context, snapshot);
            }
          }
        },
      ),
      onRefresh: refreshData,
    );
  }
  
  Widget _renderData(BuildContext context, AsyncSnapshot snapshot) {
    return new ListView.builder(
        itemBuilder: (_, i) {
          var news = snapshot.data[i];
          return new Card(
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                new Text('title:' + news['title']),
                new Image.network(news['thumbnailUrl'])
              ],
            ),
          );
        },
        itemCount: snapshot.data.length,
      );
  }
}